import machine
import time
import network
import socket
import _thread
import gc
import json

# 定义 L298N 控制引脚，作为普通数字输出引脚
input1_pin = machine.Pin(2, machine.Pin.OUT)
input2_pin = machine.Pin(3, machine.Pin.OUT)

# 定义继电器引脚
relay_pin_1 = machine.Pin(4, machine.Pin.OUT)
relay_pin_2 = machine.Pin(5, machine.Pin.OUT)
relay_pin_1.value(0)
relay_pin_2.value(0)

# 定义按钮和指示灯引脚
button_pin = machine.Pin(6, machine.Pin.IN, machine.Pin.PULL_UP)
light_pin12 = machine.Pin(12, machine.Pin.OUT)
light_pin13 = machine.Pin(13, machine.Pin.OUT)

# 初始状态设置
input1_pin.value(0)
input2_pin.value(0)
light_pin12.value(1)
light_pin13.value(1)

# 定义时间参数（秒）
forward_time = 1.0
stop_time = 0.5
reverse_time = 1.0
relay_2_open_delay = 0.5
wait_after_relay_2_open = 1.5
relay_2_close_delay = 0.5
relay_1_close_delay = 0.2

# 控制参数
control_relay = True
button_press_count = 1

# 配置文件路径
CONFIG_FILE = 'config.json'

# 从文件读取配置
def read_config():
    global forward_time, stop_time, reverse_time, relay_2_open_delay, wait_after_relay_2_open, relay_2_close_delay, relay_1_close_delay, control_relay, button_press_count
    try:
        with open(CONFIG_FILE, 'r') as f:
            config = json.load(f)
            forward_time = config.get('forward_time', forward_time)
            stop_time = config.get('stop_time', stop_time)
            reverse_time = config.get('reverse_time', reverse_time)
            relay_2_open_delay = config.get('relay_2_open_delay', relay_2_open_delay)
            wait_after_relay_2_open = config.get('wait_after_relay_2_open', wait_after_relay_2_open)
            relay_2_close_delay = config.get('relay_2_close_delay', relay_2_close_delay)
            relay_1_close_delay = config.get('relay_1_close_delay', relay_1_close_delay)
            control_relay = config.get('control_relay', control_relay)
            button_press_count = config.get('button_press_count', button_press_count)
    except (OSError, ValueError):
        pass

# 将配置保存到文件
def save_config():
    config = {
        'forward_time': forward_time,
        'stop_time': stop_time,
        'reverse_time': reverse_time,
        'relay_2_open_delay': relay_2_open_delay,
        'wait_after_relay_2_open': wait_after_relay_2_open,
        'relay_2_close_delay': relay_2_close_delay,
        'relay_1_close_delay': relay_1_close_delay,
        'control_relay': control_relay,
        'button_press_count': button_press_count
    }
    try:
        with open(CONFIG_FILE, 'w') as f:
            json.dump(config, f)
    except OSError:
        pass

# 读取配置
read_config()

# 初始化WiFi
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid='ESP32-C3', password='123456', authmode=network.AUTH_WPA_WPA2_PSK)

while not ap.active():
    time.sleep(0.1)

print(f"AP已启动，IP地址：{ap.ifconfig()[0]}")

# 创建Web服务器
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

def generate_html():
    disabled = 'disabled' if not control_relay else ''
    checked = 'checked' if control_relay else ''
    return f"""
    <html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <head><title>电机控制</title></head>
    <body>
        <h1>电机控制</h1>
        <form method="get" action="/">
            <label>正转时间：<input type="number" step="0.1" name="forward" value="{forward_time}"></label><br>
            <label>停止时间：<input type="number" step="0.1" name="stop" value="{stop_time}"></label><br>
            <label>反转时间：<input type="number" step="0.1" name="reverse" value="{reverse_time}"></label><br>
            
            <div style="opacity: 0.5" {disabled}>
                <label>2路继电器打开延时：<input type="number" step="0.1" name="relay_open" value="{relay_2_open_delay}"></label><br>
                <label>继电器打开后等待：<input type="number" step="0.1" name="wait_open" value="{wait_after_relay_2_open}"></label><br>
                <label>2路继电器关闭延时：<input type="number" step="0.1" name="relay_close" value="{relay_2_close_delay}"></label><br>
                <label>1路继电器关闭延时：<input type="number" step="0.1" name="relay1_close" value="{relay_1_close_delay}"></label><br>
            </div>
            
            <label>控制继电器：<input type="checkbox" name="control" {checked} onchange="toggleRelay(this)"></label><br>
            <label>按钮次数：<input type="number" name="count" value="{button_press_count}"></label><br>
            <input type="submit" value="保存设置">
        </form>
        <script>
            function toggleRelay(checkbox) {{
                const relayDiv = document.querySelector('div[style="opacity: 0.5"]');
                relayDiv.style.opacity = checkbox.checked ? '0.5' : '1';
                relayDiv.querySelectorAll('input').forEach(input => {{
                    input.disabled = !checkbox.checked;
                }});
            }}
        </script>
    </body>
    </html>
    """

def motor_sequence():
    # 正转
    input1_pin.value(1)
    input2_pin.value(0)
    light_pin12.value(1)
    light_pin13.value(0)
    time.sleep(forward_time)

    # 停止
    input1_pin.value(0)
    input2_pin.value(0)
    light_pin12.value(1)
    light_pin13.value(1)
    time.sleep(stop_time)

    # 反转
    input1_pin.value(0)
    input2_pin.value(1)
    light_pin12.value(0)
    light_pin13.value(1)
    time.sleep(reverse_time)

    # 停止
    input1_pin.value(0)
    input2_pin.value(0)
    light_pin12.value(1)
    light_pin13.value(1)

def button_handler():
    global control_relay, button_press_count, forward_time, stop_time, reverse_time
    press_count = 0
    while True:
        if button_pin.value() == 0:
            time.sleep_ms(50)
            if button_pin.value() == 0:
                press_count += 1
                if control_relay:
                    if button_press_count == 1:
                        relay_pin_1.value(1)
                        time.sleep(relay_2_open_delay)
                        relay_pin_2.value(1)
                        time.sleep(wait_after_relay_2_open)
                        motor_sequence()
                        time.sleep(relay_2_close_delay)
                        relay_pin_2.value(0)
                        time.sleep(relay_1_close_delay)
                        relay_pin_1.value(0)
                        press_count = 0
                    elif button_press_count == 2:
                        if press_count == 1:
                            relay_pin_1.value(1)
                        elif press_count == 2:
                            time.sleep(relay_2_open_delay)
                            relay_pin_2.value(1)
                            time.sleep(wait_after_relay_2_open)
                            motor_sequence()
                            time.sleep(relay_2_close_delay)
                            relay_pin_2.value(0)
                            time.sleep(relay_1_close_delay)
                            relay_pin_1.value(0)
                            press_count = 0
                else:
                    motor_sequence()
                    press_count = 0
                while button_pin.value() == 0:
                    pass

_thread.start_new_thread(button_handler, ())

while True:
    try:
        conn, addr = s.accept()
        request = str(conn.recv(1024))

        if 'GET /?' in request:
            params = request.split('GET /?')[1].split(' HTTP')[0]
            for param in params.split('&'):
                key, value = param.split('=')
                if key == 'forward':
                    forward_time = max(0.1, float(value))
                elif key == 'stop':
                    stop_time = max(0.1, float(value))
                elif key == 'reverse':
                    reverse_time = max(0.1, float(value))
                elif key == 'relay_open':
                    relay_2_open_delay = max(0.1, float(value))
                elif key == 'wait_open':
                    wait_after_relay_2_open = max(0.1, float(value))
                elif key == 'relay_close':
                    relay_2_close_delay = max(0.1, float(value))
                elif key == 'relay1_close':
                    relay_1_close_delay = max(0.1, float(value))
                elif key == 'control':
                    control_relay = True
                elif key == 'count':
                    button_press_count = max(1, int(value))
            if 'control' not in request:
                control_relay = False
            save_config()

        response = generate_html()
        conn.send('HTTP/1.1 200 OK\nContent-Type: text/html\n\n')
        conn.send(response)
        conn.close()
        gc.collect()
    except OSError:
        pass
    
